package com.caldremch.calhttp.http.callback;

import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.caldremch.calhttp.http.base.BaseResp;
import com.caldremch.calhttp.http.base.BaseRespData;
import com.caldremch.calhttp.http.exception.BaseException;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;

/**
 * @author Caldremch
 * @date 2018-01-19 23:22
 * @describe
 **/
public class JsonObserver<T> implements Observer<BaseRespData<T>>{

    public AbsCallback<T> mCallback;

    public JsonObserver(AbsCallback<T> callback){
        this.mCallback = callback;
    }
    @Override
    public void onSubscribe(Disposable d) {
    }
    @Override
    public void onNext(BaseRespData<T> resp) {
        Log.e("caldremch", "成功");


        if (resp.code != 0){
            handleError(resp, null);
        }else{
            mCallback.onSuccess(resp);
        }

    }

    private void handleError(@Nullable BaseRespData<T> resp, @Nullable Throwable e) {

        String toastMsg = "";
        if (resp != null){
            toastMsg = resp.msg;
        }else{
            toastMsg = "网络不给力~";
        }

        //吐司错误 限制吐司, 还有其他的错误 code
       if (mCallback.isShowErrorMsg() && !TextUtils.isEmpty(toastMsg)){
           //toast
       }

       mCallback.onError(resp, e);

    }

    @Override
    public void onError(Throwable e) {
        Log.e("caldremch", "错误");
        mCallback.onError(null, e);

    }
    @Override
    public void onComplete() {
        Log.e("caldremch", "完成");
    }


}
